package library.admin.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

/**
 * 文件上传配置
 *
 */
@Configuration
@ConfigurationProperties(prefix = "file-upload")
public class FileUploadConfig implements WebMvcConfigurer {

    /**
     * 上传路径
     */
    private String uploadPath;

    /**
     * 访问URL前缀
     */
    private String accessUrlPrefix;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 获取当前工作目录的绝对路径
        String currentDir = System.getProperty("user.dir");
        // 构建完整的文件路径
        String fullPath = currentDir + File.separator + uploadPath + File.separator;
        
        // 配置文件访问路径映射，使上传的文件可以通过URL访问
        registry.addResourceHandler(accessUrlPrefix + "/**")
                .addResourceLocations("file:" + fullPath);
                
        System.out.println("【文件上传】静态资源映射：" + accessUrlPrefix + "/** -> " + fullPath);
    }
    
    // 注释掉旧的配置
    //@Override
    //public void addResourceHandlers(ResourceHandlerRegistry registry) {
    //    registry.addResourceHandler("/uploads/**")
    //            .addResourceLocations("classpath:/uploads/");
    //}

    public String getUploadPath() {
        return uploadPath;
    }

    public void setUploadPath(String uploadPath) {
        this.uploadPath = uploadPath;
    }

    public String getAccessUrlPrefix() {
        return accessUrlPrefix;
    }

    public void setAccessUrlPrefix(String accessUrlPrefix) {
        this.accessUrlPrefix = accessUrlPrefix;
    }
}
